package com.nengchuan.kbms.dfs.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.nengchuan.config.build.AuthUtils;
import com.nengchuan.config.exception.NcException;
import com.nengchuan.kbms.common.PageServiceImpl;
import com.nengchuan.kbms.dfs.constant.BaseConstant;
import com.nengchuan.kbms.dfs.dao.DataShareMapper;
import com.nengchuan.kbms.dfs.entity.dto.DataReceivePageDTO;
import com.nengchuan.kbms.dfs.entity.dto.DataShareDTO;
import com.nengchuan.kbms.dfs.entity.dto.DataSharePageDTO;
import com.nengchuan.kbms.dfs.entity.po.DataShare;
import com.nengchuan.kbms.dfs.entity.po.DataShareUser;
import com.nengchuan.kbms.dfs.entity.vo.DataReceiveVO;
import com.nengchuan.kbms.dfs.entity.vo.DataShareVO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 文件分享 服务实现类
 * </p>
 *
 * @author abe
 * @since 2020-03-31
 */
@Service
public class DataShareServiceImpl extends PageServiceImpl<DataShareMapper, DataShare> implements DataShareService {

    @Autowired
    private DataFileService dataFileService;

    @Autowired
    private DataFolderService dataFolderService;

    @Autowired
    private DataShareUserService dataShareUserService;

    @Autowired
    private DataShareMapper dataShareMapper;

    /**
     * 分享 （目前不包含用户空间文件分享
     * // TODO 分享权限，不能分享给自己
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long share(DataShareDTO dataShareDTO) {
        Objects.requireNonNull(dataShareDTO);

        // 分享时间验证
        if (dataShareDTO.getShareBeginTime() >= dataShareDTO.getShareEndTime() ||
            dataShareDTO.getShareEndTime() < System.currentTimeMillis()) {
            // 分享结束时间必须大于分享开始时间且结束时间必须大于当前时间
            throw new NcException("错误的分享时间");
        }
        // 分享人验证
        if (CollectionUtils.isEmpty(dataShareDTO.getReceiveUserIdList())) {
            throw new NcException("分享人不能为空");
        }
        // 文件（夹）验证
        BaseConstant.BizType bizType = BaseConstant.BizType.verify(dataShareDTO.getBizType());
        assertBizExisted(bizType, dataShareDTO.getBizId());

        // 插入主表数据
        DataShare dataShare = insert(dataShareDTO);
        Long shareId = dataShare.getId();
        List<Long> receiveUserIdList = dataShareDTO.getReceiveUserIdList();
        // 插入子表数据
        List<DataShareUser> dataShareUserList = new ArrayList<>(receiveUserIdList.size());
        for (int i = 0; i < receiveUserIdList.size(); i++) {
            DataShareUser dataShareUser = new DataShareUser();
            dataShareUser.setShareId(shareId);
            dataShareUser.setSortNo(i);
            Long receiveUserId = receiveUserIdList.get(i);
            dataShareUser.setReceiveUserId(receiveUserId);
            // TODO 设置分享人用户名（如果需要
            dataShareUser.setReceiveUserName(String.valueOf(receiveUserId));
            dataShareUserList.add(dataShareUser);
        }
        dataShareUserService.saveBatch(dataShareUserList);
        return shareId;
    }

    /**
     * 我的分享
     */
    @Override
    public IPage<DataShareVO> sharePage(DataSharePageDTO dataSharePageDTO) {
        Long userId = AuthUtils.getUserId();
        dataSharePageDTO.setCreateId(userId);
        return dataShareMapper.sharePage(dataSharePageDTO);
    }

    /**
     * 分享给我
     */
    @Override
    public IPage<DataReceiveVO> receivePage(DataReceivePageDTO dataReceivePageDTO) {
        Long userId = AuthUtils.getUserId();
        dataReceivePageDTO.setReceiveUserId(userId);
        return dataShareMapper.receivePage(dataReceivePageDTO);
    }


    /**
     * 验证业务id存在（目前是文件&文件夹
     */
    private void assertBizExisted(BaseConstant.BizType bizType, Long bizId) {
        switch (bizType) {
            case d:
                dataFolderService.assertFolderExisted(bizId);
                break;
            case f:
                dataFileService.assertFileExisted(bizId);
                break;
            default:
                throw new NcException("暂不支持");
        }
    }
}
